package com.tech.util;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import net.sf.cglib.beans.BeanCopier;

/**
* @Title BeanCopierUtils.java
* @Description bean拷贝工具类
* @author willard
* @date 2018年12月19日 下午7:01:54
* @version V1.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class BeanCopierUtils {

    private static Map<String, BeanCopier> beanCopierMap = new HashMap<String, BeanCopier>();

    /**
     * @Title copyListProperties
     * @Description sourceList中所有的对象拷贝到targetList中
     * @param sourceList
     * @param targetList
     * @param clazz
     * @throws Exception
     * @since 2018年12月8日 下午9:40:39
     */
    public static void copyListProperties(List sourceList, List targetList, Class clazz) throws Exception {
        try {
            if (CollectionUtils.isEmpty(sourceList))
                throw new Exception("sourceList不能为空");
            for (Object source : sourceList) {
                Object target = clazz.newInstance();
                copyProperties(source, target);
                targetList.add(target);
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    /**
    * @Title copyProperties
    * @Description 拷贝对象
    * @param source
    * @param target
    * {@link }
    * @since 2018年12月19日 下午6:57:38
    */
    public static void copyProperties(Object source, Object target) {
        String beanKey = generateKey(source.getClass(), target.getClass());
        BeanCopier copier = null;
        if (!beanCopierMap.containsKey(beanKey)) {
            copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            beanCopierMap.put(beanKey, copier);
        } else {
            copier = beanCopierMap.get(beanKey);
        }
        copier.copy(source, target, null);
    }
    private static String generateKey(Class<?> class1, Class<?> class2) {
        return class1.toString() + class2.toString();

    }
}
